package com.gy.studyonlineapp.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Looper;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.gy.studyonlineapp.R;
import com.gy.studyonlineapp.ViewModel.JavaQsViewModel;
import com.gy.studyonlineapp.adapter.MyFragmentAdapter;
import com.gy.studyonlineapp.common.Constants;
import com.gy.studyonlineapp.common.MyApplication;
import com.gy.studyonlineapp.constants.QuestionTypeConstants;
import com.gy.studyonlineapp.constants.SharedPreference;
import com.gy.studyonlineapp.constants.VariableIds;
import com.gy.studyonlineapp.databinding.ActivityJavaquestionBinding;
import com.gy.studyonlineapp.entity.Question;
import com.gy.studyonlineapp.entity.User;
import com.gy.studyonlineapp.fragment.JavaQuestionFragment;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class JavaQuestionActivity extends AppCompatActivity {

    private JavaQsViewModel javaQsViewModel;
    private ActivityJavaquestionBinding binding;
    private List<Fragment> fragmentList = new ArrayList<>();
    private MyFragmentAdapter adapter;
    private String type;
    private String question_type;
    private String url;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_javaquestion);
        javaQsViewModel = new ViewModelProvider(this).get(JavaQsViewModel.class);
        binding.setVariable(VariableIds.java_question_id, javaQsViewModel);
        binding.setLifecycleOwner(this);
        // 获取传递过来的题目类型
        type = getIntent().getExtras().getString("type");
        question_type = getIntent().getExtras().getString("question_type");
        initData();
    }

    /**
     * 初始化题目数据
     */
    private void initData() {
        if (QuestionTypeConstants.javaQuestion.equals(question_type)) {
            url = "http://" + Constants.localhost + ":8080/get-java-question";
        } else if (QuestionTypeConstants.androidQuestion.equals(question_type)) {
            url = "http://" + Constants.localhost + ":8080/get-android-question";
        }
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .add("type", type)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            private String objectId;
            private Integer rightCnt = 0;

            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Gson gson = new Gson();
                List<Question> list = gson.fromJson(response.body().string(), new TypeToken<List<Question>>() {
                }.getType());
                if (list != null && list.size() > 0) {
                    for (int i = 0; i < list.size(); i++) {
                        String content = list.get(i).getContent();
                        String selectStr = list.get(i).getSelectItem();
                        String answer = list.get(i).getAnswer();
                        objectId = list.get(i).getId();
                        fragmentList.add(JavaQuestionFragment.newInstance(content, selectStr, answer, objectId));
                    }
                    JavaQuestionActivity.this.runOnUiThread(() -> {
                        adapter = new MyFragmentAdapter(getSupportFragmentManager(), fragmentList);
                        binding.javaViewPage.setAdapter(adapter);
                        showFragment(0);
                    });
                    runOnUiThread(() -> {
                        binding.pageInfo.setText(binding.javaViewPage.getCurrentItem() + 1 + " / " + fragmentList.size());
                    });
                    runOnUiThread(() -> {
                        binding.preBtn.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (binding.javaViewPage.getCurrentItem() - 1 >= 0) {
                                    showFragment(binding.javaViewPage.getCurrentItem() - 1);
                                    binding.pageInfo.setText(binding.javaViewPage.getCurrentItem() + 1 + " / " + fragmentList.size());
                                } else {
                                    Toast.makeText(JavaQuestionActivity.this, "已到达首页", Toast.LENGTH_SHORT).show();
                                }
                            }
                        });

                        binding.nxtBtn.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (binding.javaViewPage.getCurrentItem() + 1 < fragmentList.size()) {
                                    showFragment(binding.javaViewPage.getCurrentItem() + 1);
                                    binding.pageInfo.setText(binding.javaViewPage.getCurrentItem() + 1 + " / " + fragmentList.size());
                                } else if (binding.javaViewPage.getCurrentItem() + 1 == fragmentList.size()) {
                                    Map<String, String> userAns = ((MyApplication) getApplication()).getUserAns();
                                    Map<String, String> standardAns = ((MyApplication) getApplication()).getStandardAns();
                                    if (userAns.size() != fragmentList.size()) {
                                        Toast.makeText(JavaQuestionActivity.this, "您还有题目未完成", Toast.LENGTH_SHORT).show();
                                    } else {
                                        // 进行弹窗交卷
                                        AlertDialog.Builder builder = new AlertDialog.Builder(JavaQuestionActivity.this);
                                        builder.setTitle("提示!");
                                        builder.setMessage("确定要交卷吗？");
                                        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                // 交卷 , 验证用户输入的答案和标准答案是否一致
                                                List<String> javaMistakes = null;
                                                for (String key : userAns.keySet()) {
                                                    if (!userAns.get(key).equals(standardAns.get(key))) {
                                                        // 加入错题集
                                                        javaMistakes = ((MyApplication) getApplication()).getJavaMistakes();
                                                        javaMistakes.add(objectId);
                                                    } else {
                                                        // TODO 答对后进行处理
                                                        rightCnt++;
                                                    }
                                                }
                                                SharedPreferences sp = getSharedPreferences(SharedPreference.SHARED, Context.MODE_PRIVATE);
                                                SharedPreferences.Editor spe = sp.edit();
                                                String user = sp.getString("user", null);
                                                User json = gson.fromJson(user, User.class);
                                                Integer userId = json.getId();
                                                OkHttpClient client = new OkHttpClient();
                                                for (int i = 0; i < javaMistakes.size(); i++) {
                                                    final String errorId = javaMistakes.get(i);
                                                    String url = "http://" + Constants.localhost + ":8080/search-error";
                                                    RequestBody requestBody = new FormBody.Builder()
                                                            .add("questionId", javaMistakes.get(i))
                                                            .add("userId", String.valueOf(userId))
                                                            .build();
                                                    Request request = new Request.Builder()
                                                            .url(url)
                                                            .post(requestBody)
                                                            .build();
                                                    Call call = client.newCall(request);
                                                    call.enqueue(new Callback() {
                                                        @Override
                                                        public void onFailure(Call call, IOException e) {
                                                            System.out.println(e.getMessage() + "=============");
                                                        }

                                                        @Override
                                                        public void onResponse(Call call, Response response) throws IOException {
                                                            String error = response.body().string();
                                                            if (error.equals("")) {
                                                                String url = "http://" + Constants.localhost + ":8080/error";
                                                                OkHttpClient client = new OkHttpClient();
                                                                RequestBody requestBody = new FormBody.Builder()
                                                                        .add("questionId", errorId)
                                                                        .add("userId", String.valueOf(userId))
                                                                        .build();
                                                                Request request = new Request.Builder()
                                                                        .url(url)
                                                                        .post(requestBody)
                                                                        .build();
                                                                Call call2 = client.newCall(request);
                                                                call2.enqueue(new Callback() {
                                                                    @Override
                                                                    public void onFailure(Call call, IOException e) {
                                                                        System.out.println(e.getMessage() + "=============");
                                                                    }

                                                                    @Override
                                                                    public void onResponse(Call call, Response response) throws IOException {
                                                                        System.out.println("错题插入成功");
                                                                    }
                                                                });
                                                            }
                                                        }
                                                    });
                                                }


                                                Toast.makeText(JavaQuestionActivity.this, "您答对了" + rightCnt, Toast.LENGTH_SHORT).show();
                                                rightCnt = 0;
                                            }
                                        });
                                        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                            }
                                        });
                                        builder.show();
                                    }
                                }
                            }
                        });
                        // 收藏按钮绑定
                        binding.imageView10.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                Fragment fragment = fragmentList.get(binding.javaViewPage.getCurrentItem());
                                Bundle arguments = fragment.getArguments();
                                String objectId = arguments.getString("objectId");
                                SharedPreferences sp = getSharedPreferences(SharedPreference.SHARED, Context.MODE_PRIVATE);
                                SharedPreferences.Editor spe = sp.edit();
                                String user = sp.getString("user", null);
                                User json = gson.fromJson(user, User.class);
                                Integer userId = json.getId();
                                // 先判断是否已经收藏
                                String url = "http://" + Constants.localhost + ":8080/search-collect";
                                OkHttpClient client = new OkHttpClient();
                                RequestBody requestBody = new FormBody.Builder()
                                        .add("questionId", objectId)
                                        .add("userId", String.valueOf(userId))
                                        .build();
                                Request request = new Request.Builder()
                                        .url(url)
                                        .post(requestBody)
                                        .build();
                                Call call = client.newCall(request);
                                call.enqueue(new Callback() {
                                    @Override
                                    public void onFailure(Call call, IOException e) {
                                    }

                                    @Override
                                    public void onResponse(Call call, Response response) throws IOException {
                                        String collect = response.body().string();
                                        if (!collect.equals("")) {
                                            Looper.prepare();
                                            Toast.makeText(JavaQuestionActivity.this, "不能重复收藏", Toast.LENGTH_SHORT).show();
                                            Looper.loop();
                                        } else {
                                            String url = "http://" + Constants.localhost + ":8080/collect";
                                            OkHttpClient client = new OkHttpClient();
                                            RequestBody requestBody = new FormBody.Builder()
                                                    .add("questionId", objectId)
                                                    .add("userId", String.valueOf(userId))
                                                    .build();
                                            Request request = new Request.Builder()
                                                    .url(url)
                                                    .post(requestBody)
                                                    .build();
                                            Call call2 = client.newCall(request);
                                            call2.enqueue(new Callback() {
                                                @Override
                                                public void onFailure(Call call, IOException e) {
                                                }

                                                @Override
                                                public void onResponse(Call call, Response response) throws IOException {
                                                    Looper.prepare();
                                                    Toast.makeText(JavaQuestionActivity.this, "收藏成功", Toast.LENGTH_SHORT).show();
                                                    Looper.loop();
                                                }
                                            });
                                        }
                                    }
                                });
                            }
                        });
                    });
                }

            }
        });
    }

    // 设置索引显示fragment,
    private void showFragment(int position) {
        binding.javaViewPage.setCurrentItem(position);
    }
}